﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using Modbus.Device;

namespace EHR18
{
    public class modbusMaster : IMaster
    {
        ModbusMaster _master;
        public modbusMaster(SerialPort port)
        {
            _master = ModbusSerialMaster.CreateRtu(port);
            _master.Transport.Retries = 3;
            _master.Transport.ReadTimeout = 100;
        }
        /// <summary>
        /// 读取多个状态位
        /// </summary>
        /// <param name="slave">从机地址</param>
        /// <param name="startAddress">起始地址</param>
        /// <param name="nCoils">读取位数</param>
        /// <returns></returns>
        public bool[] ReadCoils(byte slave, ushort startAddress, ushort nCoils)
        {
            return _master.ReadCoils(slave, startAddress, nCoils);
        }
        /// <summary>
        /// 写入多个状态位
        /// </summary>
        /// <param name="slave">从机地址</param>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">写入位数组</param>
        public void WriteCoils(byte slave, ushort startAddress, bool[] data)
        {
            _master.WriteMultipleCoils(slave, startAddress, data);
        }
        /// <summary>
        /// 读取寄存器的值
        /// </summary>
        /// <param name="slave">从机地址</param>
        /// <param name="startAddress">起始地址</param>
        /// <param name="nRegister">数量</param>
        /// <returns>寄存器返回值</returns>
        public ushort[] ReadHoldingRegisters(byte slave, ushort startAddress, ushort nRegister)
        {
            return _master.ReadHoldingRegisters(slave, startAddress, nRegister);
        }
        /// <summary>
        /// 写入多个寄存器
        /// </summary>
        /// <param name="slave">从机地址</param>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">需要写入的数据</param>
        public void WriteHoldingRegisters(byte slave, ushort startAddress, ushort[] data)
        {
             _master.WriteMultipleRegisters(slave, startAddress, data);
        }
    }
}
